import { Component, ChangeDetectorRef } from "@angular/core";
import {
  NavController,
  NavParams,
  ActionSheetController,
  ToastController,
  AlertController
} from "ionic-angular";
import { SelfCheckBean } from "./bean/self-check.bean";
import { Storage } from "@ionic/storage";
import { HttpService } from "../../providers/http.service";
import { Camera, CameraOptions } from "@ionic-native/camera";
import { CommonFunc } from "../../providers/commonFunc";
import { WorkSumPage } from "../work-sum/work-sum";
import { appConfig } from "../../providers/config";
import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from "@ionic-native/file-transfer";
import { File } from "@ionic-native/file";
import * as moment from "moment";
import { PhotoViewer } from "@ionic-native/photo-viewer";
import { HomePage } from "../home/home";

@Component({
  selector: "page-self-check",
  templateUrl: "self-check.html"
})
export class SelfCheckPage {
  private showOK: boolean = false;
  private showError: boolean = false;
  private appConfig: any;
  private selfCheckBean: SelfCheckBean = new SelfCheckBean();
  private user: any;
  elevatorType: string;
  time1 = new Date().getTime() + "1";
  time2 = new Date().getTime() + "2";
  constructor(
    public navCtrl: NavController,
    private storage: Storage,
    private httpService: HttpService,
    private camera: Camera,
    private commonFunc: CommonFunc,
    private transfer: FileTransfer,
    private file: File,
    private navParams: NavParams,
    private photoViewer: PhotoViewer,
    private ActionSheet: ActionSheetController,
    public cd: ChangeDetectorRef,
    public toast: ToastController,
    public alertController: AlertController
  ) {
    this.appConfig = appConfig;
    this.elevatorType = this.navParams.get("elevatorType");
    this.storage.get("user").then(data => {
      this.user = data;
    });
    this.selfCheckBean.checkTime = moment(new Date()).format("YYYYMMDDHHmmss");
  }
  doOk(name) {
    this.selfCheckBean[name].isOk = !this.selfCheckBean[name].isOk;
    this.cd.detectChanges();
  }
  doError(name) {
    this.selfCheckBean[name].isOk = !this.selfCheckBean[name].isOk;
  }
  doCamera(name, i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(imageData => {
      //判断网络状态
      if (!this.commonFunc.hasNetWork()) {
        if (i == "c") {
          this.selfCheckBean[name].picUrl.push(imageData);
        } else {
          this.selfCheckBean[name].picUrl[i] = imageData;
        }
        return;
      }
      const options: FileUploadOptions = {};
      let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
      //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
      options.fileKey = "file";
      options.fileName = "test.jpg";
      options.mimeType = "image/jpeg";
      const fileTransfer: FileTransferObject = this.transfer.create();
      fileTransfer.upload(imageData, serverUrl, options).then(restul => {
        let aa = JSON.parse(restul["response"]);
        if (aa["status"] == 200) {
          if (aa["data"].length > 0) {
            if (i == "c") {
              this.selfCheckBean[name].picUrl.push(aa["data"]);
            } else {
              this.selfCheckBean[name].picUrl[i] = aa["data"];
            }
          }
        }
        this.cd.detectChanges();
      });
    });
  }

  doCamera2(i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(
      imageData => {
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(
          appConfig.IP_URL + appConfig.API.upload
        );
        options.fileKey = "file";
        options.fileName = "test.jpg";
        options.mimeType = "image/jpeg";
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
          let aa = JSON.parse(restul["response"]);
          if (aa["status"] == 200) {
            if (aa["data"].length > 0) {
              if (i == "c") {
                this.selfCheckBean.reportPics.push(aa["data"]);
              } else {
                this.selfCheckBean.reportPics[i] = aa["data"];
              }
            }
          }
        });
      },
      err => {
        // Handle error
      }
    );
  }

  onHold(name, param) {
    let actionSheet = this.ActionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.selfCheckBean[name].picUrl.indexOf(param);
            this.doCamera(name, i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(
              encodeURI(
                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
              ).replace("%5C", "/"),
              null,
              { share: false }
            );
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.selfCheckBean[name].picUrl.indexOf(param);
            this.selfCheckBean[name].picUrl.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => { }
        }
      ]
    });
    actionSheet.present();
  }

  onHold2(param) {
    let actionSheet = this.ActionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.selfCheckBean.reportPics.indexOf(param);
            this.doCamera2(i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(
              encodeURI(
                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
              ).replace("%5C", "/"),
              null,
              { share: false }
            );
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.selfCheckBean.reportPics.indexOf(param);
            this.selfCheckBean.reportPics.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => {
            //console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

  doSubmit() {
    if (this.commonFunc.vlidate(this.selfCheckBean, [], false)) {

      if (
        this.selfCheckBean.isPass == undefined ||
        this.selfCheckBean.isPass == null
      ) {
        let tt = this.toast.create({
          message: "请选择是否合格",
          duration: 2000,
          position: "top"
        });
        tt.present();
        return;
      }
      if (!this.selfCheckBean.maintUserSign) {
        let tt = this.toast.create({
          message: "请检查人签名",
          duration: 2000,
          position: "top"
        });
        tt.present();
        return;
      }
      if (!this.selfCheckBean.safeUserSign) {
        let tt = this.toast.create({
          message: "请使用单位电梯管理员签名",
          duration: 2000,
          position: "top"
        });
        tt.present();
        return;
      }
      this.selfCheckBean.elevatorId = this.navParams.get("elevatorId");
      this.selfCheckBean.elevatorNum = this.navParams.get("elevatorNum");
      this.selfCheckBean.maintPartyName = this.user.partyName;
      this.selfCheckBean.maintPartyId = this.user.partyId;
      this.selfCheckBean.maintPartyName = this.user.partyName;
      this.selfCheckBean.maintUserName = this.user.userName;
      this.selfCheckBean.maintUserId = this.user.id;
      this.selfCheckBean.reportPic = this.selfCheckBean.reportPics.join(",");

      this.httpService
        .addSelfCheckRecord(
          this.commonFunc.convertBeanToString(this.selfCheckBean)
        )
        .subscribe(data1 => {
          if (data1.status == 200) {
            let tt = this.toast.create({
              message: "提交成功",
              duration: 2000,
              position: "top"
            });
            tt.present().then(() => {
              this.navCtrl.setRoot(HomePage).then(() => {
                window["jQuery"](`#` + this.time1 + `1`).remove();
                window["jQuery"](`#` + this.time1 + `2`).remove();
                window["jQuery"](`#` + this.time2 + `1`).remove();
                window["jQuery"](`#` + this.time2 + `2`).remove();
                this.navCtrl
                  .getActive()
                  .getNav()
                  .remove(0);
              });
            });
          } else {
            this.commonFunc.convertBean(this.selfCheckBean);
            const alert = this.alertController.create({
              subTitle: "信息保存失败",
              buttons: ["确定"]
            });
            alert.present();
          }
        });
    } else {
      let toas = this.commonFunc.showInsideErrorToast({
        errorMessage: "请拍完所有照片"
      });
      toas.present();
      return;
    }
  }

  whaturl(url) {
    if ((url + "").indexOf("file") < 0) {
      return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
    } else {
      return url;
    }
  }

  getImgUrl(param) {
    this.selfCheckBean.maintUserSign = param.imageDate;
    this.selfCheckBean.maintUserSignTime = moment(new Date()).format(
      "YYYYMMDDHHmmss"
    );
  }

  getImgUrl2(param) {
    this.selfCheckBean.safeUserSign = param.imageDate;
    this.selfCheckBean.safeUserSignTime = moment(new Date()).format(
      "YYYYMMDDHHmmss"
    );
  }
}
